// ==UserScript==
// @name         aliexpress feedback list
// @namespace    hth
// @version      0.7
// @description  get aliexpress feedback
// @author       hth
// @updateURL    https://gitee.com/hthgit/tampermonkey/raw/master/lib/aliexpress_feedback_list.user.js
// @match        *://feedback.aliexpress.com/display/productEvaluation.*
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// @connect writewords.org.uk
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant unsafeWindow
// @grant window.close
// @grant window.focus
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';

    $(function(){

        let productIdKey = 'feedbackList_' + $('#productId').val();

        let feedbackList = GM_getValue(productIdKey) || [];
        // let maxFeedback = $('.customer-reviews').text().match(/\((\d+?)\)/)[1];
        let form = $('#l-refresh-form')[0];

        let loadReMaxNum = GM_getValue('loadReMax') || 5000;

        function getPage(page){
            return new Promise((resolve, reject) => {

                let formdata = new FormData(form);
                formdata.set('page', page);
                formdata.set('currentPage', page > 1 ? page - 1 : '');

                let data = [...formdata.entries()].reduce((o, [k, v]) => (o[k] = v, o), {})

                $.ajax({
                    type: form.method,
                    url: form.action,
                    data: data,
                    success: resolve,
                    error: reject
                });
            });
        }

        function parseFeedback(html){
            // let feedbackWarp = $('.feedback-list-wrap');
            return html.find('.feedback-item').map(function(){
                let feedback = {};
                let item = $(this);
                
                let userName = item.find('.fb-user-info .user-name a');
                feedback.userName = userName.text().trim();
                feedback.memberDetailUrl = userName.attr('href');

                let userCountry = item.find('.fb-user-info .user-country');
                feedback.userCountry = userCountry.text().trim();

                let star = item.find('.fb-main .star-view span');
                let starMatch = star.attr('style').match(/width:\s*?(\d+?)%/);
                if(starMatch){
                    feedback.star = Math.round(starMatch[1] / 20);
                }

                let orders = item.find('.fb-main .user-order-info > span');
                orders.each(function(){
                    let order = $(this);
                    let strs = order.text().trim().split(':');
                    feedback[strs[0].trim().replace(/\s/ig, '_').toLowerCase()] = (strs[1] || '').trim();
                });
                
                let buyer = item.find('.fb-main .buyer-feedback');
                let timeNew = buyer.find('.r-time-new');
                feedback.timeNew = timeNew.text().trim();
                feedback.feedback = buyer.text().replace(timeNew.text(), '').trim();

                let photos = item.find('.fb-main .pic-view-item img');
                feedback.photos = photos.map(function(){
                    return $(this).attr('src');
                }).get();

                // feedbackWarp.append(item);

                return feedback;
            }).get();
        }

        function getPageStr(page){
            return page == 0 ? '' : '：' + page;
        }
        
        function loop(page, list){
            page = page || 1;
            return getPage(page).then((val) => {

                list = list || [];

                let html = $( val.replace(/<!DOCTYPE\s.*?>/ig, '').replace(/<(\/?)(html|body|head)>/ig, '<$1div>') );

                let newList = parseFeedback(html);

                if(list.length + newList.length > loadReMaxNum){
                    return list;
                }

                list = list.concat(newList);

                let paginationNext = html.find('#complex-pager .ui-pagination-next');
                if(paginationNext.length > 0){
                    loadReviews.text(`加载评论${getPageStr(list.length)}`);
                }
                
                if(paginationNext.length > 0 && !paginationNext.hasClass('ui-pagination-disabled') && list.length < loadReMaxNum){
                    return loop(page + 1, list);
                } else {
                    return list;
                }
            })
        }
        
        let openNewTab = $('<button style="margin-left: 10px;">新页面打开</button>').on('click', function(){
            window.open(location.href);
        });

        function _loadReviews(){
            // $('.feedback-list-wrap').empty();
            // $('#complex-pager').hide();
            return loop().then(function(list){
                feedbackList = list;
                GM_setValue(productIdKey, list);
                log();
            });
        }

        function log(){
            if(feedbackList.length > 0) {
                unsafeWindow.m = feedbackList;
                console.log('feedbackList', feedbackList);
                GM_setClipboard(JSON.stringify(feedbackList));
            }
        }
        
        let loadReviews = $(`<button style="margin-left: 10px;">加载评论${getPageStr(feedbackList.length)}</button>`).on('click', _loadReviews);

        let loadReMax = $(`<input style="margin-left: 10px; width: 50px" value="${loadReMaxNum}"/>`).on('change', function(val){
            GM_setValue('loadReMax', loadReMaxNum = loadReMax.val());
        });
        
        let openWordCount = $('<button style="margin-left: 10px;">词频统计</button>').on('click', function(){
            let newWin = window.open();
            let run = function(){
                GM_xmlhttpRequest({
                    "method": "POST",
                    "url": "http://www.writewords.org.uk/word_count.asp",
                    "data": 'txt=' + feedbackList.map(v => v[wordCountKey.val()]).toString(),
                    "headers": {
                        "user-agent": navigator.userAgent,
                        "Cache-Control": "max-age=0",
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                    "onload": function (result) {
                        // console.log(result);
                        newWin.document.body.innerHTML = result.responseText;
                    }
                });
            };
            if(!feedbackList){
                _loadReviews().then(run);
            } else {
                run();
            }
        });

        let wordCountKey = $('<input style="margin-left: 10px; width: 100px" value="userCountry"/>');
        
        $('.customer-reviews').append([openNewTab, loadReviews, loadReMax, openWordCount, wordCountKey]);

        log();
    });
})();